﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataTurnClient
{
    public class XmlOperate
    {
        /// <summary>
        /// xml读取
        /// </summary>
        public static Result XmlRead(string name) 
        {
            Result t = new Result();
            try
            {
                t.MsgCode = "9004";
                t.MsgTurn = "未匹配到id";
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load("Version.xml");
                System.Xml.XmlElement root = doc.DocumentElement;
                System.Xml.XmlNodeList personNodes = root.GetElementsByTagName("Person"); //获取Person子节点集合 
                foreach (System.Xml.XmlNode node in personNodes)
                {
                    string id = ((System.Xml.XmlElement)node).GetAttribute("id");   //获取Name属性值 
                    string Value = ((System.Xml.XmlElement)node).GetElementsByTagName("Value")[0].InnerText;
                    if (id == name)
                    {
                        t.MsgCode = "9005";
                        t.MsgTurn = Value.ToString();
                        return t;
                    }
                }
                return t;
            }
            catch (Exception ex)
            {
                t.MsgCode = "9003";
                t.MsgTurn = ex.Message;
                return t;
            }
        }
        /// <summary>
        /// xml写入
        /// </summary>
        public static Result XmlWrith(string key, string keyName)
        {
            string fileName = "Version.xml";
            Result t = new Result();
            try
            {
                t.MsgCode = "9004";
                t.MsgTurn = "未匹配到id";
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(fileName);    //加载Xml文件 
                System.Xml.XmlElement root = doc.DocumentElement;   //获取根节点 
                System.Xml.XmlNodeList personNodes = root.GetElementsByTagName("Person"); //获取Person子节点集合
                foreach (System.Xml.XmlNode node in personNodes)
                {
                    System.Xml.XmlElement ele = (System.Xml.XmlElement)node;
                    if (ele.GetAttribute("id") == key)
                    {
                        System.Xml.XmlElement nameEle = (System.Xml.XmlElement)ele.GetElementsByTagName("Value")[0];
                        nameEle.InnerText = keyName;
                        t.MsgCode = "9005";
                        t.MsgTurn = "已更改";
                    }
                }
                doc.Save(fileName);
                return t;
            }
            catch (Exception ex)
            {
                t.MsgCode = "9003";
                t.MsgTurn = ex.Message;
                return t;
            }
        }
}
}
